package com.saifan.wyy_ov.ui.album.ui;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.ui.album.model.ImageGroup;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.utils.TaskUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author WangLi
 * @version V1.0
 * @date 2014年12月4日 下午11:30:03
 * @Description 相册页面
 */

public class PhotoAlbumActivity extends BaseActivity {
    private ListView folder_listView;
    private FolderAdapter folderAdapter;
    private List<ImageGroup> list;
    private ArrayList<String> selectList;
    private final int SELECT_IMG = 0;
    private Toolbar toolbar;
    private ListView albumlist;

    boolean isSingle=false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        selectList = getIntent().getStringArrayListExtra("data");
        isSingle= getIntent().getBooleanExtra("isSingle",false);
        list = new ArrayList<ImageGroup>();
        folder_listView = (ListView) findViewById(R.id.album_list);
        ImageAsyncTask task = new ImageAsyncTask();
        TaskUtil.execute(task);
        folder_listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Intent intent = new Intent(PhotoAlbumActivity.this, PhotoShowActivity.class);
                ImageGroup ig = list.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("image", ig);
                bundle.putStringArrayList("data", selectList);
                bundle.putBoolean("isSingle", isSingle);
                bundle.putInt("count", getIntent().getIntExtra("count", 5));
                intent.putExtras(bundle);
                startActivityForResult(intent, SELECT_IMG);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_IMG) {
            if (resultCode == RESULT_OK) {
                this.selectList = data.getStringArrayListExtra("data");
                Intent intent = new Intent();
                intent.putStringArrayListExtra("data", selectList);
                setResult(RESULT_OK, intent);
                PhotoAlbumActivity.this.finish();
            }
        }
    }

    private class ImageAsyncTask extends AsyncTask<Void, Void, List<ImageGroup>> {

        @Override
        protected List<ImageGroup> doInBackground(Void... params) {
            ArrayList<ImageGroup> mGruopList = new ArrayList<ImageGroup>();
            Uri mImageUri = Media.EXTERNAL_CONTENT_URI;
            ContentResolver mContentResolver = PhotoAlbumActivity.this.getContentResolver();
            // 构建查询条件，且只查询jpeg和png的图片
            StringBuilder selection = new StringBuilder();
            selection.append(Media.MIME_TYPE).append("=?");
            selection.append(" or ");
            selection.append(Media.MIME_TYPE).append("=?");
            selection.append(" or ");
            selection.append(Media.MIME_TYPE).append("=?");
            Cursor mCursor = null;
            // 路径缓存，防止多次扫描同一目录
            try {
                // 初始化游标
                mCursor = mContentResolver.query(mImageUri, new String[]{Media.DATA}, selection.toString(),
                        new String[]{"image/jpeg",  "image/jpg"}, "date_modified DESC");
                // 遍历结果
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(Media.DATA));

                    // 获取该图片的所在文件夹的路径
                    File file = new File(path);
                    String parentName = "";
                    if (file.getParentFile() != null) {
                        parentName = file.getParentFile().getName();
                    } else {
                        parentName = file.getName();
                    }
                    // 构建一个imageGroup对象
                    ImageGroup item = new ImageGroup();
                    // 设置imageGroup的文件夹名称
                    item.setDirName(parentName);
                    String parentPath = file.getParentFile().getAbsolutePath();
                    item.setDirPath(parentPath);
                    // 寻找该imageGroup是否是其所在的文件夹
                    int searchIdx = mGruopList.indexOf(item);
                    if (searchIdx >= 0) {
                        // 如果是，该组的图片数量+1
                        ImageGroup imageGroup = mGruopList.get(searchIdx);
                        imageGroup.addImage(path);
                    } else {
                        // 否则，将该对象加入到groupList中
                        item.addImage(path);
                        mGruopList.add(item);
                    }
                }
            } catch (Exception e) {
                // 输出日志
                return null;
            } finally {
                // 关闭游标
                if (mCursor != null && !mCursor.isClosed()) {
                    mCursor.close();
                }
            }

            return mGruopList;
        }

        @Override
        protected void onPostExecute(List<ImageGroup> result) {
            super.onPostExecute(result);
            if (result != null) {
                list = result;
                folderAdapter = new FolderAdapter(result, PhotoAlbumActivity.this);
                folder_listView.setAdapter(folderAdapter);
            }
        }
    }
}
